#include	"unp.h"

void
sig_chld(int signo)
{
	pid_t	pid;
	int		stat;

	pid = wait(&stat);
	printf("child %d terminated\n", pid);
	return;
}

int
main(int argc, char **argv)
{
	int					listenfd, connfd;
	pid_t				childpid;
	socklen_t			clilen;
	struct sockaddr_in	cliaddr, servaddr;
	void				sig_chld(int);
	FILE *fp;
	char				buff[MAXLINE];
	char				recvline[MAXLINE];
	char c;

	if(argc != 2)
		err_quit("Usage : DataServer <PortNumber>");

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(atoi(argv[1]));

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	Signal(SIGCHLD, sig_chld);	/* must call waitpid() */

	for ( ; ; ) {
		clilen = sizeof(cliaddr);
		connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);

		if ( (childpid = Fork()) == 0) {	/* child process */
			Close(listenfd);	/* close listening socket */

			read(connfd, recvline, MAXLINE);

			if((fp = fopen(recvline, "r")) == NULL)
			{
				printf("해당 파일이 존재하지 않거나 기타 문제로 인하여 파일을 요청할 수 없습니다.");
				return 0;
			}

			while(fscanf(fp, "%c", &c) != EOF)
			{
				snprintf(buff, sizeof(buff), "%c", c);
				Write(connfd, buff, strlen(buff));
			}
			printf("Client로 전송을 완료했습니다.\n");
			fclose(fp);
			exit(0);
		}
		Close(connfd);			/* parent closes connected socket */
	}
}
